<template>
  <div class="box">
    <div class="querybox">
      <el-input
        v-model="filters.searchBy"
        placeholder="请输入查询内容"
        style="width: 200px; right: 10px;"
        @keyup.enter.native="tag_relationList(1)"
      />
      <el-button
        type="primary"
        @click="tag_relationList(1)"
      >查询</el-button>
      <el-button
        type="primary"
        @click="add"
      >新增</el-button>
    </div>
    <el-table
      :data="tableData"
      border
    >
      <el-table-column label="类型">
        <template slot-scope="scope">
          <div>{{ objTypeTrans(scope.row.objType) }}</div>
        </template>
      </el-table-column>
      <el-table-column label="标题">
        <template slot-scope="scope">
          <div>{{ scope.row.obj.title || '' }}</div>
        </template>
      </el-table-column>
      <el-table-column label="标签">
        <template slot-scope="scope">
          <div>{{ getTags(scope.row.tags) }}</div>
        </template>
      </el-table-column>
      <!-- <el-table-column
        label="状态"
      >
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.status"
            active-text="启用"
            inactive-text="禁用"
            @change="statusChange(scope.row)"
          />
        </template>
      </el-table-column> -->
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button
            type="text"
            size="small"
            @click="viewUser(scope.row, scope.index)"
          >查看</el-button>
          <!-- <el-button type="text" size="small" @click="updUser(scope.row, scope.index)">修改</el-button> -->
          <Del-tip
            type="text"
            size="small"
          >
            <el-button type="primary" size="mini" @click="delUser(scope.row.id)">确定</el-button>
          </Del-tip>
        </template>
      </el-table-column>
    </el-table>
    <el-row style="margin-top: 10px;">
      <el-pagination
        :total="total"
        :current-page="filters.pageNum"
        :page-size="filters.pageSize"
        layout="total, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleSizeChange"
      />
    </el-row>

    <el-dialog
      :title="editType === 'add' ? '新增' : '查看'"
      :visible.sync="dialogFormVisible"
      :before-close="beforeClose"
    >
      <el-form
        v-if="editType === 'add'"
        ref="form"
        :model="form"
        :rules="rules"
        :inline="true"
      >
        <el-form-item
          label="内容类型"
          prop="objType"
          :label-width="formLabelWidth"
        >
          <el-select v-model="form.objType" placeholder="请选择" @change="objTypeChange">
            <el-option
              v-for="item in objTypeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          label="标题"
          prop="objIdTitle"
          :label-width="formLabelWidth"
        >
          <el-input
            v-model="form.objIdTitle"
            autocomplete="off"
            readonly
          >
            <i
              slot="suffix"
              class="el-icon-search el-input__icon"
              style="cursor: pointer;"
              @click="handleIconClick('class')"
            />
          </el-input>
        </el-form-item>
        <el-form-item
          label="标签"
          prop="tagIdTitle"
          :label-width="formLabelWidth"
        >
          <el-input
            v-model="form.tagIdTitle"
            autocomplete="off"
          >
            <i
              slot="suffix"
              class="el-icon-search el-input__icon"
              style="cursor: pointer;"
              @click="handleIconClick('tags')"
            />
          </el-input>
        </el-form-item>
      </el-form>
      <div v-else>
        <el-card class="box-card">
          <div
            slot="header"
            class="clearfix"
          >
            <span>基本信息</span>
          </div>
          <el-form
            :model="rowObj"
            :inline="true"
          >
            <el-form-item
              label="标题"
              :label-width="formLabelWidth"
            >
              <el-input
                v-model="rowObj.obj.title"
                autocomplete="off"
                readonly
              />
            </el-form-item>
            <el-form-item
              label="分类"
              :label-width="formLabelWidth"
            >
              <el-input
                v-model="rowObj.obj.categories"
                autocomplete="off"
                readonly
              />
            </el-form-item>
            <el-form-item
              label="主图"
              prop="thumb"
              :label-width="formLabelWidth"
            >
              <Upload
                v-model="rowObj.obj.thumb"
                style="width: 185px;"
                :img-url="rowObj.obj.thumb"
                disabled
              />
            </el-form-item>
            <el-form-item
              label="视频"
              :label-width="formLabelWidth"
            >
              <span
                v-if="rowObj.obj.media"
                style="display: inline-block; width: 185px; cursor: pointer;"
                @click="handlePlay(rowObj.obj.media)"
              ><svg-icon icon-class="video" class="svgIcon" /></span>
              <span v-else style="display: inline-block; width: 185px;">无</span>
            </el-form-item>
            <el-form-item
              label="创建时间"
              :label-width="formLabelWidth"
            >
              <el-date-picker
                v-model="rowObj.obj.created"
                type="date"
                placeholder="选择日期"
              />
            </el-form-item>
          </el-form>
        </el-card>

        <el-card class="box-card">
          <div
            slot="header"
            class="clearfix"
          >
            <span>标签</span>
            <div style="float: right;">
              <el-button size="mini" @click="handleIconClick('tags', 'singleAdd')">新增</el-button>
            </div>
          </div>
          <el-table
            :data="rowObj.tags"
            border
          >
            <el-table-column
              prop="title"
              label="标题"
            />
            <el-table-column label="操作" width="50px">
              <template slot-scope="scope">
                <el-button
                  type="text"
                  size="small"
                  @click="delOption(scope.row, scope.$index)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </div>

      <div
        slot="footer"
        class="dialog-footer"
      >
        <el-button @click="resetForm('form')">取 消</el-button>
        <el-button
          v-if="editType === 'add'"
          type="primary"
          @click="closeDialogForm('form')"
        >确 定</el-button>
      </div>

      <el-dialog
        title="观看视频"
        :visible.sync="playValVisible"
        width="30%"
        append-to-body
      >
        <video
          width="100%"
          height="200"
          controls
          :src="playVal"
        >
          <source
            :src="playVal"
            type="video/mp4"
          >
          您的浏览器不支持视频。
        </video>
        <span
          slot="footer"
          class="dialog-footer"
        >
          <el-button @click="playValVisible = false">取 消</el-button>
          <el-button
            type="primary"
            @click="playValVisible = false"
          >确 定</el-button>
        </span>
      </el-dialog>

      <el-dialog
        :title="classType === 'tags' ? '新增标签' : '新增标题'"
        :visible.sync="dialogFormVisibleAddMember"
        :before-close="filterTableDataClose"
        append-to-body
      >
        <FilterTable
          v-if="classType === 'class' && form.objType === 1"
          :data="FilterTableData"
          :query="pbe_questionList"
          :is-show-query-input="true"
          @currentSelected="currentSelected"
        >
          <el-table-column
            prop="title"
            label="标题"
          />
          <el-table-column
            prop="thumb"
            label="主图"
          >
            <template slot-scope="scope">
              <img
                :src="scope.row.thumb"
                alt=""
                width="80px"
              >
            </template>
          </el-table-column>
          <el-table-column
            prop="month"
            label="适用月龄"
          />
          <el-table-column
            prop="needVip"
            label="是否付费"
          />
          <el-table-column label="创建时间">
            <template slot-scope="scope">
              <div>{{ timeTranslateHMS(scope.row.created) }}</div>
            </template>
          </el-table-column>
          <el-table-column
            prop="categories"
            label="分类"
          />
        </FilterTable>

        <FilterTable
          v-if="classType === 'class' && form.objType === 2"
          :data="FilterTableData"
          :query="carestoreList"
          :is-show-query-input="true"
          @currentSelected="currentSelected"
        >
          <el-table-column
            prop="title"
            label="标题"
          />
          <el-table-column
            prop="thumb"
            label="主图"
          >
            <template slot-scope="scope">
              <img
                :src="scope.row.thumb"
                alt=""
                width="80px"
              >
            </template>
          </el-table-column>
          <el-table-column
            prop="month"
            label="适用月龄"
          />
          <el-table-column
            prop="needVip"
            label="是否付费"
          />
          <el-table-column label="创建时间">
            <template slot-scope="scope">
              <div>{{ timeTranslateHMS(scope.row.created) }}</div>
            </template>
          </el-table-column>
          <el-table-column
            prop="categories"
            label="分类"
          />
        </FilterTable>

        <FilterTable
          v-if="classType === 'class' && form.objType === 3"
          :data="FilterTableData"
          :query="pbe_dimensionList"
          :is-show-query-input="true"
          @currentSelected="currentSelected"
        >
          <el-table-column
            prop="code"
            label="code"
          />
          <el-table-column
            prop="name"
            label="名称"
          />
          <el-table-column
            prop="defaultValueType"
            label="defaultValueType"
          />
          <el-table-column
            prop="maxMonth"
            label="最大适用月龄"
          />
          <el-table-column
            prop="recommendTips"
            label="recommendTips"
            show-overflow-tooltip
          />
          <el-table-column label="创建时间">
            <template slot-scope="scope">
              <div>{{ timeTranslateHMS(scope.row.created) }}</div>
            </template>
          </el-table-column>
        </FilterTable>

        <FilterTable
          v-if="classType === 'class' && form.objType === 4"
          :data="FilterTableData"
          :query="items"
          :is-show-query-input="true"
          @currentSelected="currentSelected"
        >
          <el-table-column
            prop="title"
            label="标题"
          />
          <el-table-column
            prop="subTitle"
            label="子标题"
          />
          <el-table-column
            prop="linkURL"
            label="链接地址"
          />
          <el-table-column
            prop="coverURL"
            label="封面图片"
          >
            <template slot-scope="scope">
              <img
                :src="scope.row.coverURL"
                alt=""
                width="80px"
                height="72px"
              >
            </template>
          </el-table-column>
          <el-table-column
            prop="channel"
            label="渠道"
          />
          <el-table-column
            prop="categories"
            label="分类"
          />
          <el-table-column label="创建时间">
            <template slot-scope="scope">
              <div>{{ timeTranslateHMS(scope.row.created) }}</div>
            </template>
          </el-table-column>
        </FilterTable>

        <FilterTable
          v-if="classType === 'tags'"
          :data="tagsListData"
          :query="tagsList"
          :is-show-query-input="true"
          @currentSelected="currentSelected"
        >
          <el-table-column
            prop="title"
            label="标题"
          />
          <el-table-column
            prop="thumb"
            label="主图"
          >
            <template slot-scope="scope">
              <img
                :src="scope.row.thumb"
                alt=""
                width="80px"
              >
            </template>
          </el-table-column>
          <el-table-column
            prop="month"
            label="适用月龄"
          />
          <el-table-column
            prop="needVip"
            label="是否付费"
          />
          <el-table-column label="创建时间">
            <template slot-scope="scope">
              <div>{{ timeTranslateHMS(scope.row.created) }}</div>
            </template>
          </el-table-column>
          <el-table-column
            prop="categories"
            label="分类"
          />
        </FilterTable>
        <el-row style="margin-top: 10px;">
          <el-pagination
            :total="filterTableQuery.total"
            :current-page="filterTableQuery.pageNum"
            :page-size="filterTableQuery.pageSize"
            layout="total, prev, pager, next, jumper"
            @size-change="filterTableQuerySizeChange"
            @current-change="filterTableQuerySizeChange"
          />
        </el-row>

      </el-dialog>
    </el-dialog>

  </div>
</template>

<script>
import { tag_relationList, childrenDetail, tag_relationAdd, tag_relationDelete } from '@/api/tagrelation'
import { pbe_dimensionList } from '@/api/dimension'
import { pbe_questionList } from '@/api/pbe_question'
import { items } from '@/api/operation'
import { bizorg_trans } from '@/api/org'
import { carestoreList } from '@/api/carestore'
import { tagsList } from '@/api/tags'
import { productList } from '@/api/product'
import { timeTranslateHMS } from '@/utils/formatdate'
import Upload from '@/components/Upload'
import FilterTable from '@/components/FilterTable'
export default {
  name: 'Documentation',
  components: {
    Upload,
    FilterTable
  },
  data() {
    return {
      options: [],
      timeTranslateHMS,
      filters: {
        mobile: '',
        username: '',
        searchBy: '',
        pageNum: 1,
        pageSize: 10
      },
      filterTableQuery: {
        mobile: '',
        username: '',
        searchBy: '',
        pageNum: 1,
        pageSize: 10
      },
      form: {
        objId: '',
        objType: '',
        tagId: '',
        tagIdTitle: '',
        objIdTitle: '',
        categories: ''
      },
      total: 0,
      rules: {
        tagIdTitle: [
          { required: true, message: '不能为空', trigger: 'change' }
        ],
        objType: [
          { required: true, message: '不能为空', trigger: 'blur' }
        ],
        objIdTitle: [
          { required: true, message: '不能为空', trigger: 'change' }
        ]
      },
      tableData: [],
      formLabelWidth: '120px',
      dialogFormVisible: false,
      query: '',
      editType: null,
      objTypeOptions: [
        { value: 1, label: '儿心量表问题' },
        { value: 2, label: '知识库' },
        { value: 3, label: '儿心量表能区' },
        { value: 4, label: '文章条目' }
      ],
      dialogFormVisibleAddMember: false,
      FilterTableData: [],
      // FilterTableTotal: 1,
      tagsListData: [],
      tagsListTotal: 1,
      classType: null,
      rowObj: {
        obj: {},
        tags: {}
      },
      playVal: '',
      playValVisible: false,
      singleAdd: ''
      // cacheObj: {}
    }
  },
  mounted() {
    this.tag_relationList()
    // this.productList()
  },
  methods: {
    objTypeChange(val) {
      this.form.objIdTitle = ''
    },
    handlePlay(video) {
      this.playVal = video
      this.playValVisible = true
    },
    filedsTrans(type, key) {
      const obj = {
        basic: {
          title: '标题',
          categories: '分类',
          thumb: '主图',
          media: '视频',
          id: 'id',
          created: '创建时间'
        }
      }
      return obj[type][key]
    },
    // 标签列表
    tagsList(num, searchBy = '') {
      // const pageNum = this.filters.pageNum - 1
      if (num === 1) this.filterTableQuery.pageNum = 1 // 查询时，分页器数字重置为1
      const pageNum = (num || this.filterTableQuery.pageNum) - 1
      tagsList({ ...this.filterTableQuery, pageNum, searchBy }).then(res => {
        const result = res.data
        this.tagsListData = result.content
        this.filterTableQuery.total = result.totalElements
      }).catch(err => {
        console.log(err)
      })
    },
    filterTableDataClose() {
      this.filterTableQuery.pageNum = 1
      this.filterTableQuery.searchBy = ''
      this.dialogFormVisibleAddMember = false
    },
    currentSelected(val, label) {
      if (this.singleAdd === 'singleAdd') {
        const obj = { objId: this.rowObj.objId, objType: this.rowObj.objType, tagId: val }
        // this.cacheObj = obj
        tag_relationAdd(obj).then((res) => {
          this.$message({
            message: '新增成功！',
            type: 'success'
          })
          this.rowObj.tags.push({ id: val, title: label, isAdd: true })
        })
      } else if (this.classType === 'tags') {
        this.form.tagIdTitle = label
        this.form.tagId = val
      } else {
        this.form.objId = val
        this.form.objIdTitle = label
      }
      this.dialogFormVisibleAddMember = false
      // this.bizorg_add(val)
    },
    handleIconClick(val, singleAdd) {
      this.singleAdd = singleAdd
      this.classType = val
      this.dialogFormVisibleAddMember = true
      if (val === 'tags') {
        this.tagsList()
      } else {
        switch (this.form.objType) {
          case 1:
            // 儿心量表问题
            this.pbe_questionList()
            break
          case 2:
            // 知识库
            this.carestoreList()
            break
          case 3:
            // 儿心量表能区
            this.pbe_dimensionList()
            break
          case 4:
            // 文章条目
            this.items()
            break
        }
      }
    },
    // 宝妈讲堂列表
    carestoreList(num, searchBy = '') {
      // const pageNum = this.filters.pageNum - 1
      if (num === 1) this.filterTableQuery.pageNum = 1 // 查询时，分页器数字重置为1
      const pageNum = (num || this.filterTableQuery.pageNum) - 1
      carestoreList({ ...this.filterTableQuery, pageNum, searchBy }).then(res => {
        const result = res.data
        this.FilterTableData = result.content
        this.filterTableQuery.total = result.totalElements
      }).catch(err => {
        console.log(err)
      })
    },
    // 运营位列表
    items(num, keyword = '') {
      // this.filters.pageNum = pageNum || 1
      //   this.filters
      if (num === 1) this.filters.pageNum = 1 // 查询时，分页器数字重置为1
      const pageNum = (num || this.filters.pageNum) - 1
      items({ ...this.filters, pageNum, keyword }).then(res => {
        const result = res.data
        this.FilterTableData = result.content
        this.filterTableQuery.total = result.totalElements
      }).catch(err => {
        console.log(err)
      })
    },
    // 儿心量表能区列表
    pbe_dimensionList(num, searchBy = '') {
      // const pageNum = this.filters.pageNum - 1
      if (num === 1) this.filters.pageNum = 1 // 查询时，分页器数字重置为1
      const pageNum = (num || this.filters.pageNum) - 1
      pbe_dimensionList({ ...this.filters, pageNum, searchBy }).then(res => {
        const result = res.data
        this.FilterTableData = result
        // this.tableData = result.content
        this.filterTableQuery.total = result.totalElements
      }).catch(err => {
        console.log(err)
      })
    },
    // 儿心量表问题列表
    pbe_questionList(num, searchBy = '') {
      // const pageNum = this.filters.pageNum - 1
      if (num === 1) this.filters.pageNum = 1 // 查询时，分页器数字重置为1
      const pageNum = (num || this.filters.pageNum) - 1
      pbe_questionList({ ...this.filters, pageNum, searchBy }).then(res => {
        const result = res.data
        this.FilterTableData = result.content
        this.filterTableQuery.total = result.totalElements
      }).catch(err => {
        console.log(err)
      })
    },
    getTags(arr) {
      const getArr = []
      for (let i = 0; i < arr.length; i++) {
        getArr.push(arr[i].title)
      }
      return getArr.join(' & ')
    },
    objTypeTrans(val) {
      const obj = {
        1: '儿心量表问题',
        2: '知识库',
        3: '儿心量表能区',
        4: '文章条目'
      }
      return obj[val]
    },
    bizOrgChange(orgId) {
      orgId = '4028808a748b6e4f01748b71b6bf0002'
      bizorg_trans({ orgId }).then((res) => {
      })
    },
    // dialog关闭事件
    beforeClose() {
      this.resetForm('form')
    },
    // logo上传成功监听
    onSuccess(res) {
      this.form.imgUrl = res
    },
    // 生成随机数
    randomStr() {
      const str = '1234567890abcdefghijkmnpqrstuvwxyz'.split('')
      let result = ''
      for (let i = 0; i < 8; i++) {
        result += str[Math.floor((Math.random() * (str.length - 1)) + 1)]
      }
      return result
    },
    // 新增操作
    add() {
      this.form.code = this.randomStr()
      this.editType = 'add'
      this.dialogFormVisible = true
    },
    // 分页切换监听
    handleSizeChange(pageNum) {
      this.filters.pageNum = pageNum
      this.tag_relationList()
    },
    filterTableQuerySizeChange(pageNum) {
      this.filterTableQuery.pageNum = pageNum
      this.classType === 'tags' ? this.tagsList() : this.carestoreList()
    },
    // 用户列表
    tag_relationList(num) {
      // const pageNum = this.filters.pageNum - 1
      if (num === 1) this.filters.pageNum = 1 // 查询时，分页器数字重置为1
      const pageNum = (num || this.filters.pageNum) - 1
      tag_relationList({ ...this.filters, pageNum }).then(res => {
        const result = res.data
        this.tableData = result.content
        this.total = result.totalElements
      }).catch(err => {
        console.log(err)
      })
    },
    // 删除用户
    delUser(id) {
      this.editType = 'delete'
      // this.tableData.splice(row, 1)
      // this.$message({
      //   message: '删除成功！',
      //   type: 'success'
      // })
      tag_relationDelete({ itemId: id }).then((res) => {
        this.$message({
          message: '删除成功！',
          type: 'success'
        })
        this.tag_relationList()
      })
    },
    delOption(row, index) {
      this.editType = 'delete'
      const { objId, objType } = this.rowObj
      const tagId = row.id
      tag_relationDelete({ objId, objType, tagId }).then((res) => {
        this.$message({
          message: '删除成功！',
          type: 'success'
        })
        // this.tag_relationList()
        this.rowObj.tags.splice(index, 1)
        this.$message({
          message: '删除成功！',
          type: 'success'
        })
      })
    },
    // 修改用户
    updUser(row, index) {
      this.editType = 'update'
      this.dialogFormVisible = true
    },
    // 查看用户
    viewUser(row) {
      this.editType = 'view'
      this.dialogFormVisible = true
      const rowClone = JSON.parse(JSON.stringify(row))
      // rowClone.obj.categories = rowClone.obj.categories.split('|')
      this.rowObj = { ...rowClone }
      this.tagsList()
    },
    // 用户详情
    childrenDetail(childrenId) {
      childrenDetail({ childrenId }).then(res => {
        // res.data.org.logo = 'https://dss1.baidu.com/70cFfyinKgQFm2e88IuM_a/forum/pic/item/bd315c6034a85edf3d432b7d44540923dc5475a5.jpg'
        this.form = res.data
        // let result = res.data;
        // this.tableData = result.users;
      }).catch(err => {
        console.log(err)
      })
    },
    // 弹窗关闭触发函数
    closeDialogForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.tag_relationAdd(formName)
        } else {
          return false
        }
      })
    },
    resetForm(formName) {
      this.dialogFormVisible = false
      this.$refs[formName] && this.$refs[formName].resetFields()
    },
    // 新增用户
    tag_relationAdd(formName) {
      const obj = { ...this.form }
      tag_relationAdd(obj).then((res) => {
        this.$message({
          message: '新增成功！',
          type: 'success'
        })
        this.tag_relationList()
        this.resetForm(formName)
        // this.dialogFormVisible = false
      })
    },
    statusChange(row) {
      // {id: row.id, status: row.status}
    },
    // 产品列表
    productList() {
      // const pageNum = this.filters.pageNum - 1
      // { ...this.filters, pageNum }
      productList().then(res => {
        const result = res.data.content
        const arr = []
        for (let i = 0; i < result.length; i++) {
          if (result[i].name) {
            arr.push(result[i])
          }
        }
        this.options = arr
        // this.tableData = result.content
        // this.total = result.totalPages
      }).catch(err => {
        console.log(err)
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.box {
  margin: 20px 30px;
  .form {
    margin-top: 50px;
  }
  .querybox {
    text-align: right;
    margin-bottom: 20px;
  }
}
.box-card {
  margin-bottom: 15px;
}
</style>
